module storebuff (clk, rst, llegir, escriure, ple, buit, dataIn, addrIn, dataOut, addrOut);
	input clk, rst, llegir, escriure;
	input [31:0] dataIn;
	input [15:0] addrIn;
	output [31:0] dataOut;
	output [15:0] addrOut;
	output ple, buit;
	
	reg [2:0] top, i;
	reg ple, buit;
	reg [31:0] dataOut;
	reg [15:0] addrOut;
	reg [15:0] bufferAddr[7:0];
	reg [31:0] bufferData[7:0];
	
	initial
		begin		
			buit = 1;
			ple = 0;
			top = 0;
		end
	
	//Quan llegim, shiftem una posicio el contingut cap al fons, i al escriure, afegim pel final
	
	always @(posedge clk)
		if ((escriure==1) && (ple==0)) 
			begin
				bufferAddr[top] <= #1 addrIn;
				bufferData[top] <= #1 dataIn;
				top = top + 1;
			end
		else if ((llegir==1) && (buit==0))
			begin
				dataOut = bufferData[0];
				addrOut = bufferAddr[0];
				for(i=1; i<top; i = i+1) 
					begin
						bufferAddr[i-1] <=  bufferAddr[i];
						bufferData[i-1] <=  bufferData[i];
					end
				top = top - 1;
			end		
	
	always @(top) 
		if (top == 8)
			ple = 1;
		else if (top == 0)
			buit = 1;
		else
			begin
				buit = 0;
				ple = 0;
			end

	always @(rst) 
		if (rst)
			begin
				buit = 1;
				ple = 0;
				top = 0;
			end
endmodule

